package practise.alogrithm.introductionToAlogrithm;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Richard on 7/21/2014.
 */
public class TreeBuilder {
    public static TreeNode<Integer> createTreeByArrayInWidth(Integer[] arrays){
        List<TreeNode<Integer>> queue = new ArrayList<>();
        TreeNode<Integer> root=null;
        for(Integer i : arrays){
            TreeNode<Integer> newNode = new TreeNode<>();
            newNode.setValue(i);
            queue.add(newNode);
            if(queue.size()==1){
                //just set the root, when it start from one
                root= newNode;
            }
            else {
                TreeNode<Integer> topNode = queue.get(0);
                newNode.setParent(topNode);
                if(topNode.getLeft()==null){
                    topNode.setLeft(newNode);
                }
                else if(topNode.getRight()==null){
                    topNode.setRight(newNode);
                    queue.remove(0);
                }
                else{
                    queue.get(0).setLeft(newNode);
                }
            }

        }
        return root;
    }

    public static void printTreeInWidth(TreeNode<Integer> root){
        List<TreeNode<Integer>> queue = new ArrayList<>();
        queue.add(root);
        Integer level = 0;
        while (!queue.isEmpty()){
            List<TreeNode<Integer>> levelNodes = new ArrayList<>();
            level++;
            while(!queue.isEmpty()){
                levelNodes.add(queue.remove(0));
            }
            System.out.println("level:"+level);
            while (!levelNodes.isEmpty()){
                TreeNode<Integer> current = levelNodes.remove(0);
                if(current.getLeft()!=null){
                    queue.add(current.getLeft());
                }
                if(current.getRight()!=null){
                    queue.add(current.getRight());
                }
                System.out.print("["+current.getValue()+"]");
            }
            System.out.println();

        }
    }
}
